package com.jxc.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jxc.dao.BaseDaoI;
import com.jxc.model.po.OperationLog;
import com.jxc.model.po.User;
import com.jxc.model.vo.DataGrid;
import com.jxc.model.vo.VOperationLog;
import com.jxc.service.OperationLogServiceI;

@Service("operationService")
public class OperationLogServiceImpl implements OperationLogServiceI {

	@Autowired
	private BaseDaoI<OperationLog> operationLogDao;

	@Override
	public DataGrid datagrid(VOperationLog vOperationLog) {
		DataGrid dg = new DataGrid();
		dg.setRows(this.changeModel(this.find(vOperationLog)));
		dg.setTotal(this.total(vOperationLog));
		return dg;
	}

	private List<VOperationLog> changeModel(List<OperationLog> operationLogs) {
		List<VOperationLog> vOperationLogs = new ArrayList<VOperationLog>();
		if (operationLogs != null && operationLogs.size() > 0) {
			for (OperationLog log : operationLogs) {
				VOperationLog vOperationLog = new VOperationLog();
				BeanUtils.copyProperties(log, vOperationLog);
				if (log.getUser() != null) {
					User user = log.getUser();
					vOperationLog.setUid(user.getId());
					vOperationLog.setUusername(user.getUsername());
				}
				vOperationLogs.add(vOperationLog);
			}
		}
		return vOperationLogs;
	}

	private List<OperationLog> find(VOperationLog vOperationLog) {
		String hql = "from OperationLog t where 1=1 ";

		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vOperationLog, hql, values);

		if (vOperationLog.getSort() != null && vOperationLog.getOrder() != null) {
			hql += " order by " + vOperationLog.getSort() + " "
					+ vOperationLog.getOrder();
		}
		return operationLogDao.find(hql, values, vOperationLog.getPage(),
				vOperationLog.getRows());
	}

	private Long total(VOperationLog vOperationLog) {
		String hql = "select count(*) from OperationLog t where 1=1 ";
		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vOperationLog, hql, values);
		return operationLogDao.count(hql, values);
	}

	private String addWhere(VOperationLog vOperationLog, String hql,
			List<Object> values) {
		if (vOperationLog.getStartOptTime() != null) {
			hql += " and t.optTime >= ? ";
			values.add(vOperationLog.getStartOptTime());
		}
		if (vOperationLog.getEndOptTime() != null) {
			hql += " and t.optTime <= ? ";
			values.add(vOperationLog.getEndOptTime());
		}
		return hql;
	}

	@Override
	public void save(OperationLog operationLog) {
		operationLogDao.save(operationLog);
	}

}
